<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Map and Bar Chart</title>
    <link rel="stylesheet" href="../lib/d3-geomap/dist/d3-geomap.css">
    <style>
        #container {
            display: flex;
            justify-content: space-around;
            height: 100vh;
        }
        #map, #bar_chart {
            flex: 1;
            min-width: 1000px;
            min-height: 0;
        }
        .legend {
            position: absolute;
            left: 20px;
            bottom: 20px;
            background: white;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
            box-shadow: 0 0 10px rgba(0,0,0,0.2);
        }
    </style>
</head>
<body>

<h1 style="text-align: center;">Map and Bar Chart</h1>

<div>
    <input type="number" id="yearInput" value="1800" min="1800" max="2100">
    <select id="attributeSelect">
        <option value="income">Income</option>
        <option value="population">Population</option>
        <option value="lifeExpectancy">Life Expectancy</option>
    </select>
</div>

<div id="container">
    <div id="map" class="d3-geomap"></div>
    <div id="bar_chart"></div>
</div>

<script src="../lib/d3.v6.min.js"></script>
<script src="../lib/topojson.min.js"></script>
<script src="../lib/d3-geomap/dist/d3-geomap.min.js"></script>
<script src="./mapping.js" type="module"></script>
<!--  -->
<script type="module">
    import { countryMap } from "./mapping.js";
    const countryMapping = countryMap;

    let preprocessedData = {
        "income": [],
        "population": [],
        "lifeExpectancy": []
    };

    let map;

    window.onload = function() {
        d3.csv('../data/newData.csv').then(data => {
            data.forEach(d => {
                Object.keys(preprocessedData).forEach(key => {
                    let countryData = preprocessedData[key].find(country => country.name === d.name);
                    if (!countryData) {
                        countryData = {
                            name: d.name,
                            region: d.region,
                            iso3: countryMapping[d.name]
                        };
                        preprocessedData[key].push(countryData);
                    }
                    countryData[d.year] = d[key];
                });
                d.iso3 = countryMapping[d.name];
            });

            initializeMap('income');
            updateMap('1800');
            updateBarChart(1800, 'income');
        });
    };

    function initializeMap(selectedAttribute) {
        d3.select('#map').selectAll("*").remove();

        map = d3.choropleth()
            .geofile('../lib/d3-geomap/dist/topojson/world/countries.json')
            .colors(d3.schemeYlGnBu[9])
            .format(d3.format(',.02f'))
            .legend(true)
            .unitId('iso3')
            .column('1800');

        let selection = d3.select('#map').datum(preprocessedData[selectedAttribute]);
        map.draw(selection);
    }

    function updateMap(year) {
        map.column(year).update();
    }

    const margin = {top: 10, right: 30, bottom: 100, left: 40},
        width = 460 - margin.left - margin.right,
        height = 450 - margin.top - margin.bottom;

    const svg = d3.select("#bar_chart")
        .append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", `translate(${margin.left},${margin.top})`);

    function updateBarChart(year, attribute) {
        d3.csv("../data/newData.csv").then(data => {
            const filteredData = data.filter(d => d.year == year);
            const summedData = d3.rollup(filteredData, v => d3.sum(v, d => +d[attribute]), d => d.region);
            const dataArray = Array.from(summedData, ([key, value]) => ({ region: key, value }));

            const x = d3.scaleBand()
                .range([0, width])
                .domain(dataArray.map(d => d.region))
                .padding(0.2);
            svg.selectAll(".x-axis").remove();
            svg.append("g")
                .attr("class", "x-axis")
                .attr("transform", `translate(0, ${height})`)
                .call(d3.axisBottom(x))
                .selectAll("text")
                .attr("transform", "translate(-10,0)rotate(-45)")
                .style("text-anchor", "end");

            const y = d3.scaleLinear()
                .domain([0, d3.max(dataArray, d => d.value)])
                .range([height, 0]);
            svg.selectAll(".y-axis").remove();
            svg.append("g")
                .attr("class", "y-axis")
                .call(d3.axisLeft(y));

            const bars = svg.selectAll(".bar")
                .data(dataArray);
            bars.enter()
                .append("rect")
                .attr("class", "bar")
                .merge(bars)
                .attr("x", d => x(d.region))
                .attr("width", x.bandwidth())
                .attr("y", d => y(d.value))
                .attr("height", d => height - y(d.value))
                .attr("fill", "#69b3a2");

            bars.exit().remove();
        });
    }

    var yearInput = document.getElementById('yearInput');
    var attributeSelect = document.getElementById('attributeSelect');

    yearInput.addEventListener('input', function() {
        var selectedYear = parseInt(yearInput.value);
        var selectedAttribute = attributeSelect.value;
        updateMap(selectedYear);
        updateBarChart(selectedYear, selectedAttribute);
    });

    attributeSelect.addEventListener('change', function() {
        var selectedYear = parseInt(yearInput.value);
        var selectedAttribute = attributeSelect.value;
        initializeMap(selectedAttribute);
        updateBarChart(selectedYear, selectedAttribute);
    });
</script>
</body>
</html>
